package cn.net.autocode.platform.dingTalk.service;

import cn.net.autocode.core.utils.HttpClient;
import cn.net.autocode.core.utils.HttpClientFactory;
import cn.net.autocode.dbManager.Dao;
import cn.net.autocode.platform.dingTalk.config.DingTalkConfig;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@Service("platformDingTalkServ")
public class DingTalkServ {
    private JSONObject accessToken;
    private final Dao dao;
    private DingTalkConfig dingTalkConfig;

    public DingTalkServ(Dao dao) {
        this.dao = dao;
    }

    private void init(){
        if (dingTalkConfig == null) {
            dingTalkConfig = new DingTalkConfig();
            JSONObject json = dao.queryJSON("select * from dingtalk_config");
            dingTalkConfig.setAppId(json.getString("appId"));
            dingTalkConfig.setClientId(json.getString("clientId"));
            dingTalkConfig.setClientSecret(json.getString("clientSecret"));
            dingTalkConfig.setCorpId(json.getString("corpId"));
            dingTalkConfig.setRobotCode(json.getString("robotCode"));
        }
    }

    public void clean(){
        this.dingTalkConfig = null;
    }

    /**
     * 获取企业内部应用AccessToken
     */
    public String getCorpId(){
        this.init();
        return this.dingTalkConfig.getCorpId();
    }

    /**
     * 获取企业内部应用AccessToken
     */
    public String getAccessToken(){
        this.init();
        HttpClient httpClient = HttpClientFactory.create("https://api.dingtalk.com");
        String uri = "/v1.0/oauth2/accessToken";
        JSONObject param = new JSONObject();
        param.put("appKey",dingTalkConfig.getClientId());
        param.put("appSecret",dingTalkConfig.getClientSecret());

        boolean tokenValidate = false;
        if (this.accessToken!=null){
            long expireTime = this.accessToken.getLongValue("expireTime");
            if (expireTime>System.currentTimeMillis()/1000){
                tokenValidate = true;
            }
        }
        if (!tokenValidate){
            try {
                JSONObject rs = httpClient.postJson(uri,param,JSONObject.class);
                long expireTime = System.currentTimeMillis()/1000+rs.getLongValue("expireTime")-60;
                rs.put("expireTime",expireTime);
                this.accessToken = rs;
            } catch (Exception e) {
                throw new RuntimeException(e.getMessage());
            }
        }

        return this.accessToken.getString("accessToken");
    }

    /**
     * 获取用户详细信息
     */
    public String getUserIdByCode(String accessToken,String code){
        HttpClient httpClient = HttpClientFactory.create("https://oapi.dingtalk.com");
        String uri = "/topapi/v2/user/getuserinfo?access_token="+accessToken;
        JSONObject param = new JSONObject();
        param.put("code",code);
        JSONObject rs = httpClient.postJson(uri,param,JSONObject.class);
        String errcode = rs.getString("errcode");
        if("0".equals(errcode)){
            return rs.getJSONObject("result").getString("userid");
        }else{
            throw new RuntimeException(rs.getString("errmsg"));
        }
    }

    /**
     * 根据手机号获取用户ID
     */
    public String queryUserIdByMobile(String accessToken,String mobile){
        HttpClient httpClient = HttpClientFactory.create("https://oapi.dingtalk.com");
        String uri = "/topapi/v2/user/getbymobile?access_token="+accessToken;
        JSONObject param = new JSONObject();
        param.put("mobile",mobile);
        JSONObject rs = httpClient.postJson(uri,param,JSONObject.class);
        String errcode = rs.getString("errcode");
        if("0".equals(errcode)){
            return rs.getJSONObject("result").getString("userid");
        }else{
            throw new RuntimeException(rs.getString("errmsg"));
        }
    }

    /**
     * 获取用户详细信息
     */
    public JSONObject getUserInfo(String accessToken,String userid){
        HttpClient httpClient = HttpClientFactory.create("https://oapi.dingtalk.com");
        String uri = "/topapi/v2/user/get?access_token="+accessToken;
        JSONObject param = new JSONObject();
        param.put("userid",userid);
        param.put("language","zh_CN");
        JSONObject rs = httpClient.postJson(uri,param,JSONObject.class);
        String errcode = rs.getString("errcode");
        if("0".equals(errcode)){
            return rs.getJSONObject("result");
        }else{
            throw new RuntimeException(rs.getString("errmsg"));
        }
    }


    public void departmentList(String accessToken,long deptId){
        HttpClient httpClient = HttpClientFactory.create("https://oapi.dingtalk.com");
        String uri = "/topapi/v2/department/listsub?access_token="+accessToken;
        JSONObject param = new JSONObject();
        param.put("language","zh_CN");
        param.put("dept_id",deptId);
        JSONObject rs = httpClient.postJson(uri,param,JSONObject.class);
    }







    /**
     * 创建个人待办任务
     */
    public JSONObject createDbTask(String accessToken,String unionid){
        HttpClient httpClient = HttpClientFactory.create("https://api.dingtalk.com");
        String uri = "/v1.0/todo/users/"+unionid+"/tasks?operatorId="+unionid;

        Map<String,String> header = new HashMap<>();
        header.put("x-acs-dingtalk-access-token",accessToken);

        JSONObject param = new JSONObject();
        param.put("subject","LIMS不合格样品");//待办标题，必填
        param.put("description","为什么一直不出处理那，这个需要很长的信息，请立马进行处理，好好的进行处理！");//待办备注，非必填
        param.put("dueTime",System.currentTimeMillis()+3600000);//截至时间，非必填，单位毫秒
        JSONArray executorIds = new JSONArray();
        executorIds.add(unionid);
        param.put("executorIds",executorIds);//待办任务执行者
       // param.put("participantIds",executorIds);//待办任务参与者

        JSONObject notifyConfigs = new JSONObject();
        notifyConfigs.put("dingNotify","1");//发送钉钉弹窗通知
        param.put("notifyConfigs",notifyConfigs);
        param.put("reminderTimeStamp",System.currentTimeMillis()+3000000);//待办提醒时间
        JSONObject detailUrl = new JSONObject();
        detailUrl.put("appUrl","https://www.baidu.com");
        detailUrl.put("pcUrl","https://www.baidu.com");

        param.put("detailUrl",detailUrl);
        param.put("sourceId","00000002");
        return httpClient.postJson(uri,param,header,JSONObject.class);
    }

    public JSONObject createChat(String accessToken,String userId){
        HttpClient httpClient = HttpClientFactory.create("https://oapi.dingtalk.com");
        String uri = "/topapi/im/chat/scenegroup/create?access_token="+accessToken;
        JSONObject param = new JSONObject();
        param.put("title","山东大区");//群名称，长度限制为1~20个字符。
        param.put("owner_user_id",userId);//群主ID
        JSONArray useridlist = new JSONArray();
        useridlist.add(userId);
        param.put("useridlist",useridlist);
        param.put("template_id","6d19d033-3a23-4894-b8bc-0c1f9fb5205c");

        return httpClient.postJson(uri,param,JSONObject.class);
    }


    /**
     * 使用机器人发送群信息
     */
    public JSONObject sendGroupMessages(String accessToken){
        HttpClient httpClient = HttpClientFactory.create("https://api.dingtalk.com");
        String uri = "/v1.0/robot/groupMessages/send";
        Map<String,String> header = new HashMap<>();
        header.put("x-acs-dingtalk-access-token",accessToken);

        String msgParam = """
                {
                      "title": "加样审批提醒",
                      "text": "有3条待审批的加样信息",
                      "picUrl": "@lADOADmaWMzazQKA",
                      "messageUrl":"https://www.baidu.com",
                 }
                """;


        JSONObject param = new JSONObject();
        param.put("msgParam",msgParam);//消息模板参数
        param.put("msgKey","sampleLink");//消息模板key
        param.put("openConversationId","cidmhOBlFjOZTskC46pN83Cfg==");
        param.put("robotCode",dingTalkConfig.getRobotCode());//机器人的编码

        return httpClient.postJson(uri,param,header,JSONObject.class);
    }

    /**
     * 使用机器人发送ding消息
     */
    public JSONObject sendDingMessages(String accessToken){

        HttpClient httpClient = HttpClientFactory.create("https://api.dingtalk.com");
        String uri = "/v1.0/robot/ding/send";
        Map<String,String> header = new HashMap<>();
        header.put("x-acs-dingtalk-access-token",accessToken);

        JSONArray userList = new JSONArray();
        userList.add("021510694037756248");
        JSONObject param = new JSONObject();
        param.put("robotCode",dingTalkConfig.getRobotCode());//机器人的编码
        param.put("remindType",1);//DING消息类型：1：应用内DING；2：短信DING；3：电话DING
        param.put("receiverUserIdList",userList);
        param.put("content","您有3条待审批的加样信息");//消息模板参数

        return httpClient.postJson(uri,param,header,JSONObject.class);
    }




}
